/*
 * Copyright 2015-2016 Tumblr, Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tumblr.backboard.example;

import com.facebook.rebound.SpringSystem;
import com.tumblr.backboard.Actor;
import com.tumblr.backboard.MotionProperty;
import com.tumblr.backboard.Utils.View;
import com.tumblr.backboard.imitator.Imitator;
import com.tumblr.backboard.imitator.InertialImitator;
import ohos.agp.components.Component;

/**
 * Snap view to either the lower left or lower right corner.
 *
 * @author ericleong
 * @since 2021-05-07
 */
public class ConstrainedFragment extends BaseFraction {
    @Override
    public int getUiContent() {
        return ResourceTable.Layout_fragment_constrain;
    }

    @Override
    public void initComponent() {
        final Component constraintView = mComponent.findComponentById(ResourceTable.Id_constraint);

        final Component circle = mComponent.findComponentById(ResourceTable.Id_circle);
        final InertialImitator motionImitatorX =
                new InertialImitator(MotionProperty.X, Imitator.TRACK_DELTA,
                        Imitator.FOLLOW_SPRING, 0, 0);

        final InertialImitator motionImitatorY =
                new InertialImitator(MotionProperty.Y, Imitator.TRACK_DELTA,
                        Imitator.FOLLOW_SPRING, 0, 0);

        new Actor.Builder(SpringSystem.create(), circle)
                .addMotion(motionImitatorX, View.TRANSLATION_X)
                .addMotion(motionImitatorY, View.TRANSLATION_Y)
                .build();

        mComponent.setLayoutRefreshedListener(new Component.LayoutRefreshedListener() {
            @Override
            public void onRefreshed(Component component) {
                motionImitatorX.setMinValue(
                        -constraintView.getWidth() / VALUE_TWO + circle.getWidth() / VALUE_TWO);
                motionImitatorX.setMaxValue(
                        constraintView.getWidth() / VALUE_TWO - circle.getWidth() / VALUE_TWO);
                motionImitatorY.setMinValue(
                        -constraintView.getHeight() / VALUE_TWO + circle.getWidth() / VALUE_TWO);
                motionImitatorY.setMaxValue(
                        constraintView.getHeight() / VALUE_TWO - circle.getWidth() / VALUE_TWO);
                mComponent.setLayoutRefreshedListener(null);
            }
        });
    }
}
